package com.nyf.web;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.nyf.dao.DocumentDao;

import com.nyf.entity.Document;

public class MainServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Map<String,String> map = new HashMap<String, String>();
	
	static{
		map.put(".pdf", "application/pdf");
		map.put(".mp3", "audio/mp3");
		map.put(".jpg", "image/jpg");
		map.put(".jif", "image/jif");
		//....
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method=request.getParameter("m");
		if(method==null||"".equals(method)){
			list(request,response);
			
		}else if("upload".equals(method)){
			upload(request,response);
			
		}else if("download".equals(method)){
			download(request,response);
			
		}
		
	}

	private void download(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String fileName = request.getParameter("f");
		if("folder".equals(fileName)){
			
			response.sendRedirect("folder.jspx?m=list");
			
		}else{
			
		String extName = fileName.substring(fileName.lastIndexOf("."));
		
		File file = new File("H:/upload",fileName);
		
		if(!file.exists()) {
			response.sendError(404);
		} else {
			response.setContentType(map.get(extName));
			response.setContentLength((int) file.length());
			
			String encodedfileName = new String("我的文件.pdf".getBytes("UTF-8"),"ISO8859-1");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\""); 
			
			FileInputStream inputStream = new FileInputStream(file);
			
			OutputStream out = response.getOutputStream();
			
			byte[] buffer = new byte[1024];
			int len = -1;
			
			while((len = inputStream.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			
			out.flush();
			out.close();
			}
		}
	}
	private void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
		File uploadFile = new File("C:/upload");
		File tempFile = new File("C:/tempupload");
		
		if(!uploadFile.exists()) {
			uploadFile.mkdir();
		}
		
		if(!tempFile.exists()) {
			tempFile.mkdir();
		}
		
		//.......................................
		
		Document doc = new Document();
		
		
		
		if(ServletFileUpload.isMultipartContent(request)) {
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//设置缓冲区
			factory.setSizeThreshold(1024*10);
			//设置临时文件夹
			factory.setRepository(tempFile);
			
			ServletFileUpload uploader = new ServletFileUpload(factory);
			//设置允许上传的文件大小
			uploader.setFileSizeMax(1024*1024*10);
			
			try {
				List<FileItem> list = uploader.parseRequest(request);
				
				for(FileItem item : list) {
					if(item.isFormField()) {
						if("desc".equals(item.getFieldName())) {
							doc.setName(item.getString());
						}
					} else {
						//是一个文件类型的表单元素 进行文件上传操作
						
						System.out.println("name:" + item.getName()); //获取的上传文件的名字
						System.out.println("filedName:" + item.getFieldName());
						System.out.println("content-type:" + item.getContentType()); //获取文件的类型
						System.out.println("length :" + item.getSize());//获取文件的大小
						
						String name = item.getName();
						//获取扩展名
						String extendName = name.substring(name.lastIndexOf("."));
						//创建新的文件名
						String newName = UUID.randomUUID().toString() + extendName;
						Date date = new Date();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String time=sdf.format(date);
						String fileid="null";
						InputStream stream = item.getInputStream();
						
						FileOutputStream outputStream = new FileOutputStream(new File(uploadFile,newName));
						
						byte[] buffer = new byte[1024];
						int len = -1;
						
						while((len = stream.read(buffer)) != -1) {
							outputStream.write(buffer, 0, len);
						}
						outputStream.flush();
						outputStream.close();
						
						doc.setTime(time);
						doc.setName(extendName);
						doc.setFilename(newName);
						doc.setFileid(fileid);
					}
				}
				
				DocumentDao dao = new DocumentDao();
				dao.save(doc);
				
				
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("未设置enctype='multipart/form-data'");
		}		
		
		response.sendRedirect("main.jspx");
		
	}
	private void upload2(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		File uploadfile = new File("h:/upload");
		File tempfile = new File("h:/uploadtemp");
		
		if(!uploadfile.exists()) {
			uploadfile.mkdir();
		}
		
		if(!tempfile.exists()) {
			tempfile.mkdir();
		}
		
		//.......................................
		
		Document doc = new Document();
		
		
		if(ServletFileUpload.isMultipartContent(request)){
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			
			factory.setSizeThreshold(1024*10);
			
			factory.setRepository(tempfile);
			
			ServletFileUpload uploader = new ServletFileUpload(factory);
			
			uploader.setFileSizeMax(1024*1024*10);
			
			try {
				List<FileItem> list = uploader.parseRequest(request);
				for(FileItem item:list){
					if(item.isFormField()){
						if("desc".equals(item.getFieldName())) {
							doc.setName(item.getString());
						}
						
					}else{
						
						String name=item.getName();
						String extendName=name.substring(name.lastIndexOf("."));
						
						String newName = UUID.randomUUID().toString() + extendName;
						Date date = new Date();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String time=sdf.format(date);
						InputStream stream = item.getInputStream();
						String fileid="no";
						FileOutputStream outputStream = new FileOutputStream(new File(uploadfile,newName));
						
						byte[] buffer = new byte[1024];
						
						int len = -1;
						
						while((len = stream.read(buffer)) != -1) {
							outputStream.write(buffer, 0, len);
						}
						outputStream.flush();
						outputStream.close();
						
						doc.setTime(time);
						doc.setKind(extendName);
						doc.setName(name);
						doc.setFilename(newName);
						doc.setFileid(fileid);
					}
					
				}
				DocumentDao dao = new DocumentDao();
				dao.save(doc);
				
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			System.out.println("cuowu");
		}
			response.sendRedirect("main.jspx");
	}

	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// TODO Auto-generated method stub
		DocumentDao dao=new DocumentDao();
		List<Document> list=dao.findAll();
		
		request.setAttribute("list", list);
		request.getRequestDispatcher("/WEB-INF/views/main.jsp").forward(request, response);
		
	}
	
}
